#include "FileExplorerModel.h"

FileExplorerModel::FileExplorerModel(QObject *parent) :
    QAbstractTableModel(parent),
    _currentPath("/")
{

}

int FileExplorerModel::rowCount(const QModelIndex &) const
{
    return _currentPath.count();
}

int FileExplorerModel::columnCount(const QModelIndex &) const
{
    return 1;
}

QVariant FileExplorerModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::DisplayRole && index.column() == 0) {
        if(index.row() < rowCount()) {
            return _currentPath[index.row()];
        }
    }
    return QVariant();
}

bool FileExplorerModel::setData(const QModelIndex &index, const QVariant &, int role)
{
    if(role == Qt::EditRole && index.column() == 0) {
        int lastCount = rowCount();
        if(index.row() < lastCount) {
            _currentPath.setPath(_currentPath.absoluteFilePath(_currentPath[index.row()]));
            int newCount = rowCount();

            qDebug("Last Count: %d New Count %d", lastCount, newCount);

            if(lastCount < newCount) {
                insertRows(lastCount, newCount - lastCount);
                return true;
            }
            else if(lastCount > newCount) {
                removeRows(newCount, lastCount - newCount);
                return true;
            }

        }
    }
    return false;
}

Qt::ItemFlags FileExplorerModel::flags(const QModelIndex &index) const
{
    return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
}

bool FileExplorerModel::insertRows(int row, int count, const QModelIndex &parent)
{
    qDebug("row: %d count %d", row, count);
    beginInsertRows(parent, row, row+count);
    endInsertRows();
    return true;
}

bool FileExplorerModel::removeRows(int row, int count, const QModelIndex &parent)
{
    qDebug("row: %d count %d", row, count);
    beginRemoveRows(parent, row, row+count);
    endRemoveRows();
    return true;
}
